package cn.gov.mwr.szy206.command;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import cn.gov.mwr.szy206.IMessage;
import cn.gov.mwr.szy206.IMessageBody;
import cn.gov.mwr.szy206.SzyBuilder;
import cn.gov.mwr.szy206.SzyMessage;
import cn.gov.mwr.szy206.SzyMessageBody;
import cn.gov.mwr.szy206.SzyMessageHeader;
import cn.gov.mwr.szy206.SzySymbol;
import cn.gov.mwr.szy206.body.BodyDown;
import cn.gov.mwr.szy206.utils.ByteUtil;
import cn.gov.mwr.szy206.utils.CrcUtil;

public class UpCommand {

	public static int DIR = 1;// 表示由遥测站上行的报文

	public static int DIV = 0;// 0表示单报文，下发的命令，都是单报文

	public static int FCB = 3;// 3表示重发次数，默认为3次，最大为3次

	// 启用默认的延时时间设置
	public static int DELAY = 0;

	public static int SEC_METHOD = 1;

	public static int SEC_SECRET = 1;

	protected IMessage buildMessage(IMessageBody body) {

		SzyMessage message = new SzyMessage();

		SzyMessageHeader header = new SzyMessageHeader();
		header.setBodySize(body.getContent().length);

		message.setHeader(header);
		message.setBody(body);

		byte[] bytes = body.getContent();
		byte[] crcResult = CrcUtil.crc8Check(bytes);
		message.setCRC(crcResult);

		message.setEOF(SzySymbol.EOF);

		return message;

	}
	
	/**
	 * 16://设置遥测终端剩余水量报警值 3个字节的数据
	 * 
	 * @return
	 */
	public IMessage send16Message(String stcd, int data, int method, int secret) {

		SzyMessageBody messageBody = new SzyMessageBody();

		int FUNC = 0;// 发送确认命令
		byte control = SzyBuilder.newControl(DIR, DIV, FCB, FUNC);
		messageBody.setControl(control);
		messageBody.setAddress(SzyBuilder.newStcd(stcd));

		BodyDown bodyDown = new BodyDown();
		byte[] tp = SzyBuilder.newTP(DELAY);
		byte[] pw = SzyBuilder.newPW(method, secret);

		if (data > 999999 || data < 0) {
			data = 0;
		}
		String strData = StringUtils.leftPad("" + data, 6, "0");
		byte[] newdata = ByteUtil.str2Bcd(strData);
		ArrayUtils.reverse(newdata);

		bodyDown.setAFN((byte) 0x16);
		bodyDown.setData(newdata);
		bodyDown.setPw(pw);
		bodyDown.setTp(tp);

		messageBody.setUserData(bodyDown);
		return buildMessage(messageBody);
	}
	
	public static void main(String[] args){
		
	}
	
	
}
